package cn.lblbc.webbrowser

import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton

class TabGridFragment : Fragment() {
    private lateinit var tabRecyclerView: RecyclerView
    private lateinit var tabAdapter: TabGridAdapter
    private lateinit var newTabButton: FloatingActionButton
    private lateinit var addTabButton: ImageButton
    private lateinit var selectButton: ImageButton
    private lateinit var closeAllButton: ImageButton
    private lateinit var cancelSelectionButton: ImageButton
    private lateinit var closeSelectedButton: ImageButton
    private lateinit var tabCountText: TextView
    private lateinit var selectedCountText: TextView
    private lateinit var selectionBar: LinearLayout
    private lateinit var emptyStateText: TextView
    
    private var isSelectionMode = false
    private val selectedTabs = mutableSetOf<Int>()
    
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_tab_grid, container, false)
        
        initViews(view)
        setupRecyclerView()
        setupListeners()
        
        return view
    }
    
    override fun onResume() {
        super.onResume()
        updateTabCount()
        checkEmptyState()
    }
    
    private fun initViews(view: View) {
        tabRecyclerView = view.findViewById(R.id.tabRecyclerView)
        newTabButton = view.findViewById(R.id.newTabButton)
        addTabButton = view.findViewById(R.id.addTabButton)
        selectButton = view.findViewById(R.id.selectButton)
        closeAllButton = view.findViewById(R.id.closeAllButton)
        cancelSelectionButton = view.findViewById(R.id.cancelSelectionButton)
        closeSelectedButton = view.findViewById(R.id.closeSelectedButton)
        tabCountText = view.findViewById(R.id.tabCountText)
        selectedCountText = view.findViewById(R.id.selectedCountText)
        selectionBar = view.findViewById(R.id.selectionBar)
        emptyStateText = view.findViewById(R.id.emptyStateText)
    }
    
    private fun setupRecyclerView() {
        // LinearLayoutManager已在XML中设置，此处无需再设置
        // val spanCount = if (resources.displayMetrics.widthPixels > 1000) 3 else 2
        // tabRecyclerView.layoutManager = GridLayoutManager(context, spanCount)
        
        tabAdapter = TabGridAdapter(
            onTabClicked = { position ->
                if (isSelectionMode) {
                    toggleTabSelection(position)
                } else {
                    (activity as? MainActivity)?.switchToTab(position)
                    parentFragmentManager.popBackStack()
                }
            },
            onCloseTabClicked = { position ->
                (activity as? MainActivity)?.closeTab(position)
                tabAdapter.notifyItemRemoved(position)
                updateTabCount()
                checkEmptyState()
            },
            onTabLongClicked = { position ->
                if (!isSelectionMode) {
                    enterSelectionMode()
                    toggleTabSelection(position)
                }
                true
            },
            onCheckChanged = { position, isChecked ->
                if (isChecked) {
                    selectedTabs.add(position)
                } else {
                    selectedTabs.remove(position)
                }
                updateSelectedCount()
            },
            isInSelectionMode = { isSelectionMode },
            getTabCount = { (activity as? MainActivity)?.getTabCount() ?: 0 }
        )
        
        tabRecyclerView.adapter = tabAdapter
        
        // 添加上滑删除功能
        val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.UP) {
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false // 不处理移动操作
            }
            
            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                tabAdapter.onCloseTabClicked(position)
            }
        })
        itemTouchHelper.attachToRecyclerView(tabRecyclerView)
    }
    
    private fun setupListeners() {
        // 底部浮动按钮
        newTabButton.setOnClickListener {
            switchToBlankTabOrCreate()
        }
        
        // 顶部工具栏的新增标签页按钮
        addTabButton.setOnClickListener {
            switchToBlankTabOrCreate()
        }
        
        selectButton.setOnClickListener {
            enterSelectionMode()
        }
        
        closeAllButton.setOnClickListener {
            (activity as? MainActivity)?.closeAllTabs()
            checkEmptyState()
        }
        
        cancelSelectionButton.setOnClickListener {
            exitSelectionMode()
        }
        
        closeSelectedButton.setOnClickListener {
            val sortedPositions = selectedTabs.sortedDescending()
            for (position in sortedPositions) {
                (activity as? MainActivity)?.closeTab(position)
            }
            exitSelectionMode()
            updateTabCount()
            checkEmptyState()
        }
    }
    
    private fun switchToBlankTabOrCreate() {
        val mainActivity = activity as? MainActivity
        if (mainActivity != null) {
            // 查找是否已存在空白标签页
            var blankTabFound = false
            for (i in 0 until mainActivity.getTabCount()) {
                val fragment = mainActivity.getTabFragment(i)
                if (fragment is WebViewFragment && fragment.getCurrentUrl() == "about:blank") {
                    // 如果找到空白标签页，切换到它
                    mainActivity.switchToTab(i)
                    blankTabFound = true
                    break
                }
            }
            
            // 如果没有找到空白标签页，创建一个新的
            if (!blankTabFound) {
                mainActivity.addBlankTab()
            }
            
            // 关闭标签页网格视图
            parentFragmentManager.popBackStack()
        }
    }
    
    private fun enterSelectionMode() {
        isSelectionMode = true
        selectionBar.visibility = View.VISIBLE
        addTabButton.visibility = View.GONE
        selectButton.visibility = View.GONE
        closeAllButton.visibility = View.GONE
        selectedTabs.clear()
        tabAdapter.notifyDataSetChanged()
        updateSelectedCount()
    }
    
    private fun exitSelectionMode() {
        isSelectionMode = false
        selectionBar.visibility = View.GONE
        addTabButton.visibility = View.VISIBLE
        selectButton.visibility = View.VISIBLE
        closeAllButton.visibility = View.VISIBLE
        selectedTabs.clear()
        tabAdapter.notifyDataSetChanged()
    }
    
    private fun toggleTabSelection(position: Int) {
        if (selectedTabs.contains(position)) {
            selectedTabs.remove(position)
        } else {
            selectedTabs.add(position)
        }
        tabAdapter.notifyItemChanged(position)
        updateSelectedCount()
    }
    
    private fun updateSelectedCount() {
        selectedCountText.text = getString(R.string.selected_count, selectedTabs.size)
    }
    
    private fun updateTabCount() {
        val tabCount = (activity as? MainActivity)?.getTabCount() ?: 0
        tabCountText.text = getString(R.string.tabs_count, tabCount)
    }
    
    private fun checkEmptyState() {
        val tabCount = (activity as? MainActivity)?.getTabCount() ?: 0
        if (tabCount == 0) {
            tabRecyclerView.visibility = View.GONE
            emptyStateText.visibility = View.VISIBLE
        } else {
            tabRecyclerView.visibility = View.VISIBLE
            emptyStateText.visibility = View.GONE
        }
    }
    
    fun refreshTabs() {
        tabAdapter.notifyDataSetChanged()
        updateTabCount()
        checkEmptyState()
    }
    
    class TabGridAdapter(
        private val onTabClicked: (Int) -> Unit,
        val onCloseTabClicked: (Int) -> Unit,
        private val onTabLongClicked: (Int) -> Boolean,
        private val onCheckChanged: (Int, Boolean) -> Unit,
        private val isInSelectionMode: () -> Boolean,
        private val getTabCount: () -> Int
    ) : RecyclerView.Adapter<TabGridAdapter.TabViewHolder>() {
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TabViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_tab_card, parent, false)
            return TabViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: TabViewHolder, position: Int) {
            val mainActivity = holder.itemView.context as? MainActivity
            val fragment = mainActivity?.getTabFragment(position)
            
            if (fragment is WebViewFragment) {
                holder.tabTitle.text = fragment.getTitle()
                // 设置网页缩略图
                val thumbnail = fragment.getThumbnail()
                if (thumbnail != null) {
                    holder.tabPreview.setImageBitmap(thumbnail)
                } else {
                    holder.tabPreview.setImageResource(R.drawable.bg)
                }
                // 在实际应用中，这里可以设置网页的缩略图和favicon
                holder.tabFavicon.setImageResource(R.drawable.ic_globe)
            } else if (fragment is HomeFragment) {
                holder.tabTitle.text = "主页"
                holder.tabPreview.setImageResource(R.drawable.bg)
                holder.tabFavicon.setImageResource(R.drawable.ic_home)
            }
            
            holder.itemView.setOnClickListener { onTabClicked(position) }
            holder.closeTabButton.setOnClickListener { onCloseTabClicked(position) }
            holder.itemView.setOnLongClickListener { onTabLongClicked(position) }
            
            // 处理选择模式
            if (isInSelectionMode()) {
                holder.tabCheckBox.visibility = View.VISIBLE
                holder.closeTabButton.visibility = View.GONE
            } else {
                holder.tabCheckBox.visibility = View.GONE
                holder.closeTabButton.visibility = View.VISIBLE
            }
            
            holder.tabCheckBox.setOnCheckedChangeListener(null)
            holder.tabCheckBox.isChecked = false
            holder.tabCheckBox.setOnCheckedChangeListener { _, isChecked ->
                onCheckChanged(position, isChecked)
            }
        }
        
        override fun getItemCount(): Int {
            return getTabCount()
        }
        
        class TabViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val tabPreview: ImageView = itemView.findViewById(R.id.tabPreview)
            val tabFavicon: ImageView = itemView.findViewById(R.id.tabFavicon)
            val tabTitle: TextView = itemView.findViewById(R.id.tabTitle)
            val closeTabButton: ImageButton = itemView.findViewById(R.id.closeTabButton)
            val tabCheckBox: CheckBox = itemView.findViewById(R.id.tabCheckBox)
        }
    }
}